package cn.cloud.mqtt2redis.configuration.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfiguration extends CachingConfigurerSupport {

    private Logger logger = LoggerFactory.getLogger(RedisConfiguration.class);

    @Bean(name= "jedis.pool")
    @Autowired
    public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config,
                               @Value("${jedis.pool.host}")String host,
                               @Value("${jedis.pool.port}")int port,
                               @Value("${jedis.pool.database}")int database) {
        JedisPool jedisPool = new JedisPool(config,host,port);
        logger.info("JedisPool注入成功！");
        logger.info("redis地址：" + host + ":" + port+ ":" + database);

        if(! init_redis(jedisPool,database)) {
            logger.error("redis2地址：" + host + ":" + port + "清零操作失败");
            System.exit(-1);
        }
        return jedisPool;
    }

    @Bean(name= "jedis.pool.config")
    public JedisPoolConfig jedisPoolConfig (@Value("${jedis.pool.config.maxTotal}")int maxTotal,
                                            @Value("${jedis.pool.config.maxIdle}")int maxIdle,
                                            @Value("${jedis.pool.config.maxWaitMillis}")int maxWaitMillis) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        return config;
    }

    private boolean init_redis(JedisPool jedisPool,int database) {
        Jedis jedis = jedisPool.getResource();
        jedis.select(database);
        if(jedis.flushDB()==null){
            logger.info("redis init failed...");
            jedis.close();
            return false;
        }
        jedis.close();
        return true;
		
    }
}
